package com.example.demo.controller.jpa;

import com.example.demo.dao.PersonRepository;
import com.example.demo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class JpaCurdController {

    @Autowired
    PersonRepository personRepository;

    @RequestMapping("/savePerson")
    public Person savePerson(@RequestBody Person person) {
        personRepository.save(person);
        return person;
    }

    @RequestMapping("/findById")
    public Person findById(Long id) {
        Optional<Person> personOptional = personRepository.findById(id);
        return personOptional.get();
    }

    @RequestMapping("/deleteById")
    public String deleteById(Long id) {
        personRepository.deleteById(id);
        return "删除成功";
    }

//    条件查找
    @RequestMapping(value="/findByName", method = {RequestMethod.GET, RequestMethod.POST})
    public Person findByName(String name) {
        CompletableFuture<Person> byName = personRepository.findByName(name);
        try {
            Person person = byName.get();
            return person;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
//    public Person findByName(String name) {
//        return personRepository.findByName(name).get();
//    }

    @RequestMapping("/findByAgeGreaterThan")
    public List<Person> findByAgeGreaterThan(int age) {
        return personRepository.findByAgeGreaterThan(age);
    }

    @RequestMapping("/findByNameCustomQuery")
    public Optional<Person> findByNameCustomQuery(String name){
        return personRepository.findByNameCustomQuery(name);
    }
    @RequestMapping("/findPersonNameById")
    public String findPersonNameById(Long id){
        return personRepository.findPersonNameById(id);
    }
    @RequestMapping("/updatePersonNameById")
    @Transactional
    public Integer updatePersonNameById(String name, Long id){
        Integer person = personRepository.updatePersonNameById(name, id);
        return person;
    }
}
